<template>
  <el-form v-if="obj.show" ref="formRuleRef" :model="form" style="margin-top:1em" :class="center?css.center:css.default" :rules="formRules">
    <el-form-item v-if="!props.disableSelectClass" label="选择班级" prop="selectClass">
      <el-select :disabled="props.disableEdit" popper-class="pop_height" style="width: 35em" v-model="form.selectClass" value-key="id" filterable
                 placeholder="只能为你管理的班级创建考试">
        <el-option v-for="item in obj.manageClassList" :label="item.name" :value="item" :key="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item  label="考试时间" prop="examTime">
      <el-date-picker :disabled="props.disableEdit" v-model="form.examTime" type="datetimerange" start-placeholder="开始时间"
                      end-placeholder="结束时间"></el-date-picker>
    </el-form-item>

    <el-form-item label="考试名称" prop="examName">
      <el-input :disabled="props.disableEdit" placeholder="最长30个字" v-model="form.examName"></el-input>
    </el-form-item>

    <el-form-item label="及格分数比例" prop="passScore">
      <el-input :disabled="props.disableEdit" placeholder="输入50代表50%，不可超过100，默认60" v-model="form.passScore"></el-input>
    </el-form-item>

    <el-form-item v-show="!disableEdit">
      <div style="width: 100%;display: flex;flex-direction: row;justify-content: center">
        <el-button @click="createExam(formRuleRef)" type="primary" style="width: 39%">{{props.btnText}}</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {Class, Exam, User} from "../../types/mytypes";
import {ClassRequest, ExamRequest} from "../../request/MyRequset";
import {UserStore} from "../../store/store";
import {FormInstance, FormRules} from "element-plus";
import {ISODateToMysqlTime} from "../../tools/mysqlTool";

interface propType{
  btnText:string,
  disableEdit:boolean,
  center:boolean,
  exam:Exam|undefined,
  disableSelectClass:boolean
}
const props = withDefaults(defineProps<propType>(),{
  btnText:"创建",
  disableEdit:false,
  center:false,
  exam:undefined,
  disableSelectClass:false
})
const css = reactive({
  center:"form_center",
  default:"form"
})
const formRuleRef = ref<FormInstance>();
const formRules = reactive<FormRules>({
  examName: [
    {required: true, message: "请输入考试名"},
    {min: 3, max: 30, message: "考试名的长度需在3-30之间"},
  ],
  passScore: [
    {
      asyncValidator: (rule, value) => {
        return new Promise((resolve, reject) => {
          if (isNaN(value)) {
            reject("必须是数字")
          } else if (value < 0 || value > 100) {
            reject("范围只能是0-100")
          } else {
            resolve();
          }
        })
      }
    }
  ],
  selectClass: [
    {
      required: true,
      type: "object",
      fields: {id: {type: "number", required: true, message: "还没有选择班级"}},
      message: "请选择班级"
    }
  ],
  examTime: [
    {required: true, message: "请选择考试时间"}
  ]
})
const form = reactive({
  selectClass: {} as Class,
  examName: '',
  passScore: 60,
  examTime: [] as Array<Date>
});
const obj = reactive({
  user: {} as User,
  manageClassList: [] as Array<Class>,
  show: false
})
onMounted(async () => {
  obj.user = UserStore.getUser();
  obj.manageClassList = (await ClassRequest.userGetManageAll(obj.user.id)).data;
  obj.show = true
  if(props.exam != undefined){
    form.examName = props.exam.name;
    form.passScore = props.exam.pass_score;
    form.examTime[0] = new Date(props.exam.start_time);
    form.examTime[1] = new Date(props.exam.end_time);
  }
})
const emit = defineEmits(["error", "close","update"])

const createExam = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  //console.log("createExam()")
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      switch (props.btnText){
        case "创建":
          let addRes = await ExamRequest.add(
              form.selectClass.id,
              form.examName,
              ISODateToMysqlTime(form.examTime[0].toISOString()),
              ISODateToMysqlTime(form.examTime[1].toISOString()),
              form.passScore,
              obj.user.id
          );
         // console.log(addRes)
          if (addRes.suc) {
            emit("close");
          } else {
            emit("error", addRes.message);
          }
          break;
        case "更新":
          let updateRes = await ExamRequest.update(
              (props.exam as Exam).id,
              ISODateToMysqlTime(form.examTime[0].toISOString()),
              ISODateToMysqlTime(form.examTime[1].toISOString()),
              form.examName,
              form.passScore
          )
          if (updateRes.suc) {
            emit("update");
          } else {
            emit("error", updateRes.message);
          }
          break;
        default:
          console.error("btnText填写不符合规范");
      }
    } else {
      console.log("验证不通过")
    }
  })
}
</script>

<style scoped lang="scss">
.pop_height {
  height: 100px
}
.form_center{
  display: flex;
  flex-direction: column;
  align-items: center;
  .el-form-item {
    width: 30em;

    .el-form-item__content {
      justify-content: center;
    }
  }
}
.form {
  display: flex;
  flex-direction: column;

  .el-form-item {
    width: 30em;

    .el-form-item__content {
      justify-content: center;
    }
  }
}

</style>